/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.permission.template.impl;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.service.permission.PermissionOperationTypeEnum;
import com.je.rbac.service.permission.PermissionTypeEnum;
import com.je.rbac.service.permission.template.PcFuncButtonService;
import com.je.rbac.service.permission.template.PermissionPcFuncButtonTemplateEnum;
import com.je.rbac.service.permission.template.PermissionPcFuncTemplateEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PcFuncButtonServiceImpl extends AbstractPermissionTemplateService implements PcFuncButtonService {

    @Autowired
    private MetaService metaService;

    @Override
    public String formatPcFuncButtonShowTemplate(String funcCode, String buttonCode) {
        return formatTemplate(PermissionPcFuncButtonTemplateEnum.FUNC_PC_BUTTON_SHOW.getTemplate(),
                Entry.build("funcCode", funcCode), Entry.build("buttonCode", buttonCode));
    }

    @Override
    public String formatPcFuncButtonUpdateTemplate(String funcCode, String buttonCode) {
        return formatTemplate(PermissionPcFuncButtonTemplateEnum.FUNC_PC_BUTTON_UPDATE.getTemplate(),
                Entry.build("funcCode", funcCode), Entry.build("buttonCode", buttonCode));
    }

    @Override
    public String formatPcFuncButtonDeleteTemplate(String funcCode, String buttonCode) {
        return formatTemplate(PermissionPcFuncButtonTemplateEnum.FUNC_PC_BUTTON_DELETE.getTemplate(),
                Entry.build("funcCode", funcCode), Entry.build("buttonCode", buttonCode));
    }

    @Override
    public DynaBean writePcFuncButtonShowPermission(String funcCode, String buttonCode, boolean checkDb) {
        if (checkDb) {
            DynaBean bean = metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder().eq("PERM_CODE", formatPcFuncButtonShowTemplate(funcCode, buttonCode)));
            if (bean != null) {
                return bean;
            }
        }
        return writePcFuncPermissionWithoutOutput(PermissionTypeEnum.BUTTON_PC, PermissionPcFuncButtonTemplateEnum.FUNC_PC_BUTTON_SHOW.getName(),
                formatPcFuncButtonShowTemplate(funcCode, buttonCode), funcCode, PermissionOperationTypeEnum.SHOW);
    }

    @Override
    public DynaBean findPcFuncButtonShowPermission(String funcCode, String buttonCode) {
        return metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder()
                .eq("PERM_CODE", formatPcFuncButtonShowTemplate(funcCode, buttonCode)));
    }

    @Override
    public List<DynaBean> findPcFuncButtonShowPermission(String funcCode, List<String> buttonCodeList) {
        List<String> permCodeList = new ArrayList<>();
        for (String each : buttonCodeList) {
            permCodeList.add(formatPcFuncButtonShowTemplate(funcCode, each));
        }
        return metaService.select("JE_RBAC_PERM", ConditionsWrapper.builder()
                .in("PERM_CODE", permCodeList));
    }

    @Override
    public DynaBean writePcFuncButtonUpdatePermission(String funcCode, String buttonCode, boolean checkDb) {
        if (checkDb) {
            DynaBean bean = metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder().eq("PERM_CODE", formatPcFuncButtonUpdateTemplate(funcCode, buttonCode)));
            if (bean != null) {
                return bean;
            }
        }
        return writePcFuncPermissionWithoutOutput(PermissionTypeEnum.BUTTON_PC, PermissionPcFuncButtonTemplateEnum.FUNC_PC_BUTTON_UPDATE.getName(),
                formatPcFuncButtonUpdateTemplate(funcCode, buttonCode), funcCode, PermissionOperationTypeEnum.UPDATE);
    }

    @Override
    public DynaBean findPcFuncButtonUpdatePermission(String funcCode, String buttonCode) {
        return metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder()
                .eq("PERM_CODE", formatPcFuncButtonUpdateTemplate(funcCode, buttonCode)));
    }

    @Override
    public List<DynaBean> findPcFuncButtonUpdatePermission(String funcCode, List<String> buttonCodeList) {
        List<String> permCodeList = new ArrayList<>();
        for (String each : buttonCodeList) {
            permCodeList.add(formatPcFuncButtonUpdateTemplate(funcCode, each));
        }
        return metaService.select("JE_RBAC_PERM", ConditionsWrapper.builder()
                .in("PERM_CODE", permCodeList));
    }

    @Override
    public DynaBean writePcFuncButtonDeletePermission(String funcCode, String buttonCode, boolean checkDb) {
        if (checkDb) {
            DynaBean bean = metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder().eq("PERM_CODE", formatPcFuncButtonDeleteTemplate(funcCode, buttonCode)));
            if (bean != null) {
                return bean;
            }
        }
        return writePcFuncPermissionWithoutOutput(PermissionTypeEnum.BUTTON_PC, PermissionPcFuncButtonTemplateEnum.FUNC_PC_BUTTON_DELETE.getName(),
                formatPcFuncButtonDeleteTemplate(funcCode, buttonCode), funcCode, PermissionOperationTypeEnum.DELETE);
    }

    @Override
    public DynaBean findPcFuncButtonDeletePermission(String funcCode, String buttonCode) {
        return metaService.selectOne("JE_RBAC_PERM", ConditionsWrapper.builder()
                .eq("PERM_CODE", formatPcFuncButtonDeleteTemplate(funcCode, buttonCode)));
    }

    @Override
    public List<DynaBean> findPcFuncButtonDeletePermission(String funcCode, List<String> buttonCodeList) {
        List<String> permCodeList = new ArrayList<>();
        for (String each : buttonCodeList) {
            permCodeList.add(formatPcFuncButtonDeleteTemplate(funcCode, each));
        }
        return metaService.select("JE_RBAC_PERM", ConditionsWrapper.builder()
                .in("PERM_CODE", permCodeList));
    }

    @Override
    public List<DynaBean> writePcFuncButtonPermission(String funcCode, String buttonCode, boolean update, boolean delete) {
        List<String> permCodeList = Lists.newArrayList(
                formatPcFuncButtonShowTemplate(funcCode, buttonCode)
        );
        if (update) {
            permCodeList.add(formatPcFuncButtonUpdateTemplate(funcCode, buttonCode));
        }
        if (delete) {
            permCodeList.add(formatPcFuncButtonDeleteTemplate(funcCode, buttonCode));
        }
        List<DynaBean> beanList = metaService.select("JE_RBAC_PERM", ConditionsWrapper.builder().in("PERM_CODE", permCodeList));

        //此处逻辑在于校验单个权限的添加是否还需要校验，用于提升性能，不用每个添加都查询数据库
        DynaBean showBean = null;
        DynaBean updateBean = null;
        DynaBean deleteBean = null;
        for (DynaBean eachBean : beanList) {
            if (formatPcFuncButtonShowTemplate(funcCode, buttonCode).equals(eachBean.getStr("PERM_CODE"))) {
                showBean = eachBean;
                continue;
            }

            if (update && formatPcFuncButtonUpdateTemplate(funcCode, buttonCode).equals(eachBean.getStr("PERM_CODE"))) {
                updateBean = eachBean;
                continue;
            }
            if (delete && formatPcFuncButtonDeleteTemplate(funcCode, buttonCode).equals(eachBean.getStr("PERM_CODE"))) {
                deleteBean = eachBean;
                continue;
            }
        }

        List<DynaBean> resultList = new ArrayList<>();
        if (showBean != null) {
            resultList.add(showBean);
        } else {
            resultList.add(writePcFuncButtonShowPermission(funcCode, buttonCode, false));
        }

        if (update) {
            if (updateBean != null) {
                resultList.add(updateBean);
            } else {
                resultList.add(writePcFuncButtonUpdatePermission(funcCode, buttonCode, false));
            }
        }

        if (delete) {
            if (deleteBean != null) {
                resultList.add(deleteBean);
            } else {
                resultList.add(writePcFuncButtonDeletePermission(funcCode, buttonCode, false));
            }
        }
        return resultList;
    }

    @Override
    public List<DynaBean> findPcFuncButtonPermission(String funcCode, boolean update, boolean delete) {
        List<String> operatorList = Lists.newArrayList(PermissionOperationTypeEnum.SHOW.getCode());
        if (update) {
            operatorList.add(PermissionOperationTypeEnum.UPDATE.getCode());
        }
        if (delete) {
            operatorList.add(PermissionOperationTypeEnum.DELETE.getCode());
        }
        return metaService.select("JE_RBAC_PERM", ConditionsWrapper.builder()
                .eq("PERM_OBJECT", funcCode).in("PERM_OPERATE_CODE", operatorList));
    }

    @Override
    public List<DynaBean> findPcFuncButtonPermission(String funcCode, List<String> buttonCodeList, boolean update, boolean delete) {
        List<String> operatorList = Lists.newArrayList(PermissionOperationTypeEnum.SHOW.getCode());
        if (update) {
            operatorList.add(PermissionOperationTypeEnum.UPDATE.getCode());
        }
        if (delete) {
            operatorList.add(PermissionOperationTypeEnum.DELETE.getCode());
        }

        List<String> formatButtonTemplates = new ArrayList<>();
        for (String eachButtonCode : buttonCodeList) {
            formatButtonTemplates.add(formatPcFuncButtonShowTemplate(funcCode, eachButtonCode));
            if (update) {
                formatButtonTemplates.add(formatPcFuncButtonUpdateTemplate(funcCode, eachButtonCode));
            }
            if (delete) {
                formatButtonTemplates.add(formatPcFuncButtonDeleteTemplate(funcCode, eachButtonCode));
            }
        }

        return metaService.select("JE_RBAC_PERM", ConditionsWrapper.builder()
                .eq("PERM_OBJECT", funcCode)
                .in("PERM_OPERATE_CODE", operatorList)
                .in("PERM_CODE", formatButtonTemplates));
    }

    @Override
    public void modifyPermCode(String funcCode, String oldButtonCode, String newButtonCode) {
        List<String> operatorList = Lists.newArrayList(PermissionOperationTypeEnum.SHOW.getCode(),
                PermissionOperationTypeEnum.UPDATE.getCode(),
                PermissionOperationTypeEnum.DELETE.getCode());
        List<String> formatButtonTemplates = Lists.newArrayList(formatPcFuncButtonShowTemplate(funcCode, oldButtonCode),
                formatPcFuncButtonUpdateTemplate(funcCode, oldButtonCode),
                formatPcFuncButtonDeleteTemplate(funcCode, oldButtonCode));
        List<DynaBean> oldPermBeanList = metaService.select("JE_RBAC_PERM", ConditionsWrapper.builder()
                .eq("PERM_OBJECT", funcCode)
                .in("PERM_OPERATE_CODE", operatorList)
                .in("PERM_CODE", formatButtonTemplates));
        for (int i = 0; oldPermBeanList != null && !oldPermBeanList.isEmpty() && i < oldPermBeanList.size(); i++) {
            if (PermissionOperationTypeEnum.SHOW.getCode().equals(oldPermBeanList.get(i).getStr("PERM_OPERATE_CODE"))) {
                oldPermBeanList.get(i).set("PERM_CODE", formatPcFuncButtonShowTemplate(funcCode, newButtonCode));
            } else if (PermissionOperationTypeEnum.UPDATE.getCode().equals(oldPermBeanList.get(i).getStr("PERM_OPERATE_CODE"))) {
                oldPermBeanList.get(i).set("PERM_CODE", formatPcFuncButtonUpdateTemplate(funcCode, newButtonCode));
            } else if (PermissionOperationTypeEnum.DELETE.getCode().equals(oldPermBeanList.get(i).getStr("PERM_OPERATE_CODE"))) {
                oldPermBeanList.get(i).set("PERM_CODE", formatPcFuncButtonDeleteTemplate(funcCode, newButtonCode));
            }
            metaService.update(oldPermBeanList.get(i));
        }
    }

    @Override
    public Map<String, List<DynaBean>> findPcFuncButtonVPermission(String roleId, List<String> funcCodeList) {
        Map<String, List<DynaBean>> resultMap = new HashMap<>();
        List<DynaBean> resultList = metaService.select("JE_RBAC_VROLEPERM", ConditionsWrapper.builder().eq("JE_RBAC_ROLE_ID", roleId).in("PERM_OBJECT", funcCodeList));
        List<DynaBean> splittedBeanList;
        for (DynaBean eachBean : resultList) {
            if (Strings.isNullOrEmpty(eachBean.getStr("PERM_OBJECT"))) {
                continue;
            }
            if (resultMap.containsKey(eachBean.getStr("PERM_OBJECT"))) {
                splittedBeanList = resultMap.get(eachBean.getStr("PERM_OBJECT"));
            } else {
                splittedBeanList = new ArrayList<>();
                resultMap.put(eachBean.getStr("PERM_OBJECT"), splittedBeanList);
            }
            splittedBeanList.add(eachBean);
        }
        return resultMap;
    }

}
